package com.puffer.core.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecurityFilter implements Filter {

	private String displayName;
	private String staticResources;

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession(true);
		String uri = request.getRequestURI();
		
		//如果存在静态资源路径，则跳过权限验证
		if(uri.contains(staticResources)){
			arg2.doFilter(arg0, arg1);
			return;
		}

		Enumeration<String> atts = session.getAttributeNames();

		boolean exists = false;
		// 遍历所有的session 元素
		for (Enumeration<String> e = atts; e.hasMoreElements();) {
			String attName = e.nextElement().toString();

			// 判断是否有sysUser元素
			if ("user".equals(attName)) {
				exists = true;
			}
		}
		// 判断session中存在user的情况
		if (exists) {
			if (uri.endsWith(displayName) || uri.endsWith(displayName + "/")) {
				response.sendRedirect(request.getContextPath() + "/page/FrameAll.jsp");
			}
			arg2.doFilter(arg0, arg1);
			return;
		}
		//判断用户不存在的情况
		if(uri.endsWith(displayName) || uri.endsWith(displayName + "/")){
			arg2.doFilter(arg0, arg1);
			return;
		}
		//response.sendRedirect(request.getContextPath() + "/login.jsp");
		request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(arg0, arg1);
		return ;
	}

	public void init(FilterConfig arg0) throws ServletException {
		displayName = arg0.getInitParameter("displayName");
		staticResources = arg0.getInitParameter("staticResources");
		

	}

}
